#include "TaskManager.h"

namespace Impp
{

TaskManager::TaskManager(Oscar* oscar) :
	oscar(oscar)
{
	Start(2000);
}

TaskManager::~TaskManager()
{
	std::vector<Task*>::iterator dIter(tasks.begin()); 
	while (dIter != tasks.end()) { 
	    delete (*dIter);
	     ++dIter;
	}
}

void TaskManager::addTask(Task* task){
	tasks.push_back(task);
}

Task* TaskManager::getTask(const TaskHandle & type, const qword & handle){
	std::vector<Task*>::iterator dIter(tasks.begin()); 
	for (; dIter != tasks.end(); ++dIter) { 
	      if((*dIter)->handleEquals(type,handle)){
	    	  return (*dIter);
	    	  wxLogTrace(wxT("TASKMANAGER"),wxT("TaskManager::getTask: handle found"));
	      }
	}
	return NULL;
}

Task* TaskManager::getTask(const TaskType & type){
	std::vector<Task*>::iterator dIter(tasks.begin()); 

	while (dIter != tasks.end()) { 
		Task* cur = *dIter;
		if(cur->getType() == type){
			return cur;
		}
	    ++dIter;
	}
	return NULL;
}

void TaskManager::getTasks(const TaskType & type,std::vector<Task*> & returnTasks){
	
	std::vector<Task*>::iterator dIter(tasks.begin()); 

	while (dIter != tasks.end()) { 
		Task* cur = *dIter;
		if(cur->getType() == type){
			returnTasks.push_back(cur);
		}
	    ++dIter;
	}
}

void TaskManager::deleteTask(Task* task){
	std::vector<Task*>::iterator dIter(tasks.begin()); 
	
	while (dIter != tasks.end()) { 
	      if((*dIter)==task){
	    	  wxLogTrace(wxT("TASKMANAGER"),wxT("TaskManager::deleteTask: Task to deleted found"));
	    	  delete (*dIter);
	    	  dIter = tasks.erase(dIter);
	    	  wxLogTrace(wxT("TASKMANAGER"),wxT("TaskManager::deleteTask: Task deleted"));
	    	  return;
	      }else{
	    	  ++dIter;
	      }
	}
	
	wxLogDebug(wxT("TaskManager::deleteTask: Task not found!!!"));
	
}

void TaskManager::Notify(){
	//wxLogTrace(wxT("TASKMANAGER"),wxT("TaskManager::Notify called"));
	
	std::vector<Task*>::iterator dIter(tasks.begin()); 
	time_t now = wxDateTime::GetTimeNow();
	
	if(tasks.size() > 0){
		while (dIter != tasks.end()) { 
		      if((*dIter)->checkForTimeOut(now)){
		    	  delete (*dIter);
		    	  dIter = tasks.erase(dIter);
		    	  wxLogTrace(wxT("TASKMANAGER"),wxT("TaskManager::Notify: Task timed out"));
		      }else{
		    	  ++dIter;
		      }
		}
	}
	
}

}
